package com.gskj.msmservice.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.gskj.msmservice.service.IMsmService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Map;

/**
 * @author :CodingFarmer_码农  Connor(康纳)_郭
 * @date : 10:08 20.5.21
 * @Company : http://www.gskj.com
 * @Version : 1.0
 */
@Service
public class MsmServiceImpl implements IMsmService {

    @Override
    public boolean sendTextMessage(Map<String, Object> param, String phone) {

        if (StringUtils.isEmpty(phone)) return false;

        DefaultProfile profile =
                DefaultProfile.
                        getProfile("default", "LTAI4G5VAxtZAb5cZCUQCXfQ", "ktIxiT9knB6yeKAdhY3cyojZTYNbOi");
        // 发送短信对象
        IAcsClient client = new DefaultAcsClient(profile);

        // 设置相关固定参数
        CommonRequest request = new CommonRequest();
        //request.setProtocol(ProtocolType.HTTPS);
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");

        // 设置发送信息相关参数
        request.putQueryParameter("PhoneNumbers", phone);
        request.putQueryParameter("SignName", "我的妈妈在线育儿平台"); // 申请阿里云的 签名名称
        request.putQueryParameter("TemplateCode", "SMS_190791023"); // 申请阿里云的 模板code

        // 将 存放在 map中验证码 转为 json格式
        String jsonString = JSONObject.toJSONString(param);
        // 必须传入 json字符
        request.putQueryParameter("TemplateParam", jsonString); // 发送的验证码 #{code}中 code值

        try {
            // 获取响应
            CommonResponse response =
                    client.getCommonResponse(request);

            return response.getHttpResponse().isSuccess();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
}
